package com.fagp.mew.cms.controller.permission;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fagp.mew.cms.messages.PageRequest;
import com.fagp.mew.cms.messages.PageResponse;
import com.mew.common.dc.mapper.AdminMapper;
import com.mew.common.dc.mapper.AdminRoleMapper;
import com.mew.common.entity.back.Admin;
import com.mew.common.entity.back.AdminRole;
import com.mew.common.util.MD5Encrypt;
import com.mew.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.security.RolesAllowed;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RolesAllowed({"ADMIN"})
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @ResponseBody
    @RequestMapping("/all")
    public PageResponse all(PageRequest p) {
        List<Admin> adminRoles = adminMapper.getAdminRoles();
        List<Admin> list = adminRoles.stream().collect(Collectors.toMap(Admin::getId, a -> a, (a1, a2) -> {
            a1.setRolename(a1.getRolename() + " " + a2.getRolename());
            return a1;
        })).values().stream().collect(Collectors.toList());
        return new PageResponse(list);
    }

    @ResponseBody
    @RequestMapping("/ban")
    public PageResponse ban(Integer id, Integer state) {
        state = null == state ? 1 : (state == 0 ? 1 : 0);
        int i = adminMapper.updateById(Admin.builder().id(id).state(state).build());

        return new PageResponse(i != 0);
    }

    @ResponseBody
    @RequestMapping("/role")
    public PageResponse role(Integer adminId, Integer[] roleIds) {
        adminRoleMapper.delete(new LambdaQueryWrapper<AdminRole>().eq(AdminRole::getAdminId, adminId));
        for (Integer roleId : roleIds) {
            adminRoleMapper.insert(AdminRole.builder().adminId(adminId).roleId(roleId).build());
        }
        return new PageResponse();
    }

    @ResponseBody
    @RequestMapping("/add")
    public PageResponse add(Admin admin) {
        System.out.println(admin);
        //密码
        if (StringUtils.isNotEmpty(admin.getPassword())) {
            admin.setPassword(MD5Encrypt.MD5(admin.getPassword()));
        } else {
            admin.setPassword(null);
        }

        //更新
        if (null != admin.getId()) {
            adminMapper.updateById(admin);
        } else {
            if (StringUtils.isNotEmpty(admin.getPassword())) {
                adminMapper.insert(admin);
            }
        }
        return new PageResponse();
    }
}
